<?php
/**
 * 查询构建器 find() select()
 * ORM get() all()
 */

namespace app\api\model;


use app\common\enum\FlagEnum;

class Product extends BaseModel
{
//    protected $append = [
//        'specifications',
//    ];

    protected $hidden = [
        'delete_time', 'update_time',
        'create_time', 'main_img_id', 'from', 'pivot',
    ];

    public function image()
    {
        return $this->hasMany('ProductImage', 'product_id', 'id');
    }

    public function skuList()
    {
        return $this->hasMany('Sku', 'product_id', 'id');
    }

    public function skuSpecs()
    {
        return $this->hasMany('SkuSpecs', 'product_id', 'id');
    }


    public static function getAll($page=1, $size=15)
    {
        return self::with(['sku_list', 'image'])->order('create_time desc')
            ->paginate($size, true, ['page' => $page]);
    }

    public function property()
    {
        return $this->hasMany('ProductProperty', 'product_id', 'id');
    }

    // public function getSpecificationsAttr($value, $data) {
    //     $temp = [];
    //     // $temp = self::with(['sku_specs'])->select();
    //     // $temp = array_unique($temp);
    //     return $temp;
    // }

    public function getImgAttr($value, $data)
    {
        return $this->img_prefix($value, $data);
    }

//    public function getFlagAttr($value, $data)
//    {
//        if($data['is_spu'] == FlagEnum::Single) {
//            return FlagEnum::Single;
//        }
//        return FlagEnum::Multiple;
//    }

    public static function getRecent($size)
    {
        return self::with('sku_list,image')->limit($size)->order('update_time', 'desc')->select();
    }

    public static function getDetailByID2($id)
    {
        return self::with([
            'image' => function($query){
                $query->where('status', '=', '1')->order('order', 'desc');
            }
        ])->find($id);
    }



    public static function getDetailByID($id)
    {
        return self::with('sku_list,image')->find($id);
    }

    public static function getDetailByCategoryID($id)
    {
        return self::with(['sku_list', 'image'])->where('root_category_id', '=', $id)->select();
    }
}